export function extractDominantColorBase64(base64Src: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image()

    // 统一处理逻辑
    const processImage = () => {
      try {
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d', { willReadFrequently: true })!

        // 尺寸优化：保持比例限制在[100, 200]区间
        const TARGET_SIZE = Math.min(
          200,
          Math.max(100, Math.hypot(img.naturalWidth, img.naturalHeight))
        )
        const scaleFactor = TARGET_SIZE / Math.hypot(img.naturalWidth, img.naturalHeight)
        canvas.width = Math.floor(img.naturalWidth * scaleFactor)
        canvas.height = Math.floor(img.naturalHeight * scaleFactor)

        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data

        const colorMap = new Map<string, number>()
        let bestColor = 'rgb(255,255,255)'
        let maxWeight = 0

        // 智能采样间隔（基于图像复杂度）
        const step = canvas.width * canvas.height > 50000 ? 4 : 2

        // RGB饱和度计算函数
        const getSaturation = (r: number, g: number, b: number) => {
          const max = Math.max(r, g, b)
          return max === 0 ? 0 : (max - Math.min(r, g, b)) / max
        }

        // 相对亮度计算（WCAG标准）
        const getLuminance = (r: number, g: number, b: number) =>
          0.2126 * r + 0.7152 * g + 0.0722 * b

        for (let i = 0; i < pixels.length; i += step * 4) {
          const r = pixels[i]
          const g = pixels[i + 1]
          const b = pixels[i + 2]

          // 过滤条件：排除极端颜色
          if (r + g + b < 30 || (r > 230 && g > 230 && b > 230)) continue

          // 计算视觉特征
          const saturation = getSaturation(r, g, b)
          const luminance = getLuminance(r, g, b)

          // 智能筛选条件（保持颜色鲜明且不过深）
          const isValid = saturation > 0.25 && luminance > 50 && luminance < 200
          if (!isValid) continue

          // 颜色聚类（合并相近色相）
          const clusterKey = `${Math.round(r / 20) * 20},${Math.round(g / 20) * 20},${
            Math.round(b / 20) * 20
          }`

          // 动态权重计算（饱和度 + 亮度组合）
          const weight =
            (colorMap.get(clusterKey) || 0) +
            1 +
            saturation * 15 +
            (luminance > 150 ? 5 : luminance / 30)

          colorMap.set(clusterKey, weight)

          // 更新最佳颜色（优先高权重颜色）
          if (weight > maxWeight) {
            maxWeight = weight
            bestColor = `rgb(${r},${g},${b})`
          }
        }

        // 颜色增强处理（保持RGB格式）
        let [r, g, b] = bestColor.match(/\d+/g)!.map(Number)

        // 亮度提升算法（保证最小可视亮度）
        const MIN_LUMINANCE = 120
        const currentLum = getLuminance(r, g, b)
        if (currentLum < MIN_LUMINANCE) {
          const ratio = (MIN_LUMINANCE + 50) / currentLum // 柔和提升
          r = Math.min(255, Math.round(r * ratio))
          g = Math.min(255, Math.round(g * ratio))
          b = Math.min(255, Math.round(b * ratio))
        }

        // 饱和度增强（非线性提升）
        const max = Math.max(r, g, b)
        const boost = (v: number) => {
          const delta = max - v
          return v + delta * (max > 200 ? 0.3 : 0.15)
        }
        const boosted = [boost(r), boost(g), boost(b)]

        resolve(boosted.join(','))
      } catch (error) {
        reject(new Error('Image processing failed'))
      }
    }

    // 事件绑定
    img.onload = processImage
    img.onerror = () => reject(new Error('Image load error'))

    // 触发加载
    img.src = base64Src

    // 兼容立即加载完成的情况
    if (img.complete) processImage()
  })
}
